import { getUserCarList, addOrUpdateAmount, deleteUserCar } from "@/service/api/member.js"
import { GetUsableOrderProjectList } from "@/service/api/order.js"
import store from "@/store/index.js"
import { eventBus } from "@/utils/eventBus.js"
import storage from "@/uni-sub-base/utils/storage.js"
let getCartTimer = null
const cartUtil = {
    //获取总数
    getCartTotal(data, callBack) {
        let total = {
            totalNum: 0,
            totalPrice: 0,
            totalSpace: 0,
        }
        let space = []
        data.forEach((e) => {
            e.SubItems.forEach((item) => {
                total.totalNum += item.TotalAmount
                total.totalPrice += item.TotalMoney
                space.push(item.ProductId)
                //统计种类
                // let findSpace = space.find((productId) => {
                // 	return productId == item.ProductId
                // })
                // if (!findSpace) {
                // 	space.push(item.ProductId)
                // }
            })
        })
        total.totalPrice = total.totalPrice.toFixed(2)
        total.totalSpace = space.length
        callBack(total)
    },
    //获取选择总数
    getCartTotalForSelect(data, ids, callBack) {
        let total = {
            totalNum: 0,
            totalPrice: 0,
            totalSpace: 0,
            totalSum: 0,
        }
        let space = []
        //数据处理
        data.forEach((e) => {
            e.SubItems.forEach((item) => {
                let findResult = ids.find((id) => {
                    return id == String(item.ID)
                })
                if (findResult) {
                    //统计数量
                    total.totalNum += item.TotalAmount
                    //统计金额
                    total.totalPrice += item.TotalMoney
                    total.totalSum += item.Amount
                    //统计种类
                    // let findSpace = space.find((productId) => {
                    // 	return productId == item.ProductId
                    // })
                    // if (!findSpace) {
                    // 	space.push(item.ProductId)
                    // }
                    space.push(item.ProductId)
                }
            })
        })
        total.totalPrice = total.totalPrice.toFixed(2)
        total.totalSpace = space.length
        callBack(total)
    },
    //获取购物车
    getUserCarList: (isSet = true, OrderType, priceType) => {
        return new Promise((resolve, reject) => {
            let param = {
                priceType: 1,
            }
            if (OrderType) {
                param.OrderType = OrderType
            }
            if (priceType) {
                param.priceType = priceType
            }
            // TODO 获取商城模式
            let webInfo = storage.getCache("webInfo")
            let supplierMode = -1
            if (webInfo) {
                supplierMode = webInfo.SupplierMode || 0
            }
            if (supplierMode == 1) {
                param.groupType = 2
            }
            getUserCarList(param).then((res) => {
                let items = []
                if (res && res.Data && res.Data.length > 0) {
                    res.Data.forEach((e) => {
                        let filterItem = items.filter((item) => {
                            return item.ProductId == e.ProductId
                        })
                        if (filterItem.length < 1) {
                            let SubItems = []
                            SubItems.push(e)
                            let obj = {
                                SupplierId: e.SupplierId,
                                SupplierName: e.SupplierName,
                                ProductId: e.ProductId,
                                V_Title: e.V_Title,
                                V_ThumbnailUrl160: e.V_ThumbnailUrl160,
                                SubItems: SubItems,
                            }
                            items.push(obj)
                        } else {
                            filterItem[0].SubItems.push(e)
                        }
                    })
                }
                resolve(items)
                eventBus.$emit("SET_CART", items)
                eventBus.$emit("SET_CART_FOR_SUB", items)
            })
        })
    },
    //获取购物车(供应商)
    getSupplierCarList: (isSet = true) => {
        return new Promise((resolve, reject) => {
            let param = {
                priceType: 1,
                groupType: 2,
            }
            getUserCarList(param).then((res) => {
                let items = []
                let supplierItems = []

                if (res && res.Data && res.Data.length > 0) {
                    // 同一商品归总
                    res.Data.forEach((e) => {
                        let filterItem = items.filter((item) => {
                            return item.ProductId == e.ProductId
                        })
                        if (filterItem.length < 1) {
                            let SubItems = []
                            SubItems.push(e)
                            let obj = {
                                SupplierId: e.SupplierId,
                                SupplierName: e.SupplierName,
                                ProductId: e.ProductId,
                                V_Title: e.V_Title,
                                V_ThumbnailUrl160: e.V_ThumbnailUrl160,
                                SubItems: SubItems,
                            }
                            items.push(obj)
                        } else {
                            filterItem[0].SubItems.push(e)
                        }
                    })
                    //同一供应商归总
                    items.forEach((e) => {
                        let supplierFilterItem = supplierItems.filter((item) => {
                            return item.SupplierId == e.SupplierId
                        })
                        if (supplierFilterItem.length < 1) {
                            let ProductItems = []
                            ProductItems.push(e)
                            let obj = {
                                SupplierName: e.SupplierName,
                                SupplierId: e.SupplierId,
                                ProductId: e.ProductId,
                                V_Title: e.V_Title,
                                V_ThumbnailUrl160: e.V_ThumbnailUrl160,
                                ProductItems: ProductItems,
                            }
                            supplierItems.push(obj)
                        } else {
                            supplierFilterItem[0].ProductItems.push(e)
                        }
                    })
                }
                resolve(supplierItems)
                if (isSet) {
                    store.commit("SET_SUPPLIER_CART", supplierItems)
                    eventBus.$emit("SET_SUPPLIER_CART", supplierItems)
                    eventBus.$emit("SET_SUPPLIER_CART_FOR_SUB", items)
                }
            })
        })
    },
    //获取总数(供应商)
    getSupplierCartTotal(data, callBack) {
        let total = {
            totalNum: 0,
            totalPrice: 0,
            totalSpace: 0,
        }
        let space = []
        data.forEach((e) => {
            e.ProductItems.forEach((em) => {
                em.SubItems.forEach((item) => {
                    total.totalNum += item.Amount
                    total.totalPrice += item.V_FactPrice * item.Amount
                    //统计种类
                    let findSpace = space.find((productId) => {
                        return productId == item.ProductId
                    })
                    if (!findSpace) {
                        space.push(item.ProductId)
                    }
                })
            })
        })
        total.totalPrice = total.totalPrice.toFixed(2)
        total.totalSpace = space.length
        callBack(total)
    },
    //获取选择总数(供应商)
    getSupplierCartTotalForSelect(data, ids, callBack) {
        let total = {
            totalNum: 0,
            totalPrice: 0,
            totalSpace: 0,
        }
        let space = []
        //数据处理
        data.forEach((supp) => {
            supp.ProductItems.forEach((e) => {
                e.SubItems.forEach((item) => {
                    let findResult = ids.find((id) => {
                        return id == String(item.ID)
                    })
                    if (findResult) {
                        //统计数量
                        total.totalNum += item.Amount
                        //统计金额
                        total.totalPrice += item.V_FactPrice * item.Amount
                        //统计种类
                        let findSpace = space.find((productId) => {
                            return productId == item.ProductId
                        })
                        if (!findSpace) {
                            space.push(item.ProductId)
                        }
                    }
                })
            })
        })
        total.totalPrice = total.totalPrice.toFixed(2)
        total.totalSpace = space.length
        callBack(total)
    },

    // 获取指定供应商购物车商品数量及价格
    getMarkSupplierCarList: (supplierId) => {
        return new Promise((resolve, reject) => {
            let param = {
                priceType: 1,
                supplierId: supplierId,
            }
            getUserCarList(param).then((res) => {
                if (res && res.Data) {
                    let num = 0,
                        totalPrice = 0,
                        ids = ""
                    let list = []
                    if (res.Data.length > 0) {
                        res.Data.forEach((e) => {
                            num += e.Amount
                            totalPrice += e.Amount * e.V_FactPrice
                            ids += e.ID + ","

                            let filterItem = list.filter((item) => {
                                return item.ProductId == e.ProductId
                            })
                            if (filterItem.length < 1) {
                                let SubItems = []
                                SubItems.push(e)
                                let obj = {
                                    SupplierId: e.SupplierId,
                                    SupplierName: e.SupplierName,
                                    ProductId: e.ProductId,
                                    V_Title: e.V_Title,
                                    V_ThumbnailUrl160: e.V_ThumbnailUrl160,
                                    SubItems: SubItems,
                                }
                                list.push(obj)
                            } else {
                                filterItem[0].SubItems.push(e)
                            }
                        })
                    }
                    let data = {
                        num,
                        totalPrice,
                        ids,
                    }
                    data.totalPrice = data.totalPrice.toFixed(2)
                    data.list = list
                    resolve(data)
                } else {
                    this.easyToast(res.Msg)
                }
            })
        })
    },
    //增量更新需要先去找购物车，匹配后增加份数
    getNewParam(param) {
        if (store.state.cartData && store.state.cartData.length > 0) {
            param.forEach((pa) => {
                store.state.cartData.forEach((cart) => {
                    if (cart.ProductId == pa.ProductId) {
                        cart.SubItems.forEach((sub) => {
                            if (sub.UnitId == pa.UnitId && sub.SkuId == pa.SkuId) {
                                pa.Amount += sub.Amount
                            }
                        })
                    }
                })
            })
        }
        return param
    },
    /**
     * 更新购物车
     * param 参数
     * isAdd 是否是增量更新
     */
    updateCart: (param, isAdd = false, isTime = true, orderType, priceType) => {
        return new Promise((resolve, reject) => {
            let path
            if (orderType) {
                path = "?orderType=" + orderType
            } else {
                path = "?orderType=-1"
            }
            if (isAdd) {
                param = cartUtil.getNewParam(param)
            }
            if (isTime) {
                clearTimeout(getCartTimer)
                getCartTimer = setTimeout((e) => {
                    addOrUpdateAmount(param, path).then((res) => {
                        if (orderType == 23) {
                            cartUtil.getUserCarList(true, orderType).then((res) => {
                                // uni.hideLoading()
                                resolve(res)
                            })
                        } else if (priceType) {
                            cartUtil.getUserCarList(true, false, priceType).then((res) => {
                                // uni.hideLoading()
                                resolve(res)
                            })
                        } else {
                            cartUtil.getUserCarList().then((res) => {
                                // uni.hideLoading()
                                resolve(res)
                            })
                        }
                    })
                }, 300)
            } else {
                addOrUpdateAmount(param, path).then((res) => {
                    if (orderType == 23) {
                        cartUtil.getUserCarList(true, orderType).then((res) => {
                            // uni.hideLoading()
                            resolve(res)
                        })
                    } else if (priceType) {
                        cartUtil.getUserCarList(true, false, priceType).then((res) => {
                            // uni.hideLoading()
                            resolve(res)
                        })
                    } else {
                        cartUtil.getUserCarList().then((res) => {
                            // uni.hideLoading()
                            resolve(res)
                        })
                    }
                })
            }
        })
    },
    /**
     * 更新购物车(供应商)
     * param 参数
     * isAdd 是否是增量更新
     */
    updateSupplierCart: (param, isAdd = false, isTime = true) => {
        return new Promise((resolve, reject) => {
            if (isAdd) {
                param = cartUtil.getNewParam(param)
            }
            if (isTime) {
                clearTimeout(getCartTimer)
                getCartTimer = setTimeout((e) => {
                    addOrUpdateAmount(param).then((res) => {
                        cartUtil.getSupplierCarList().then((res) => {
                            // uni.hideLoading()
                            resolve(res)
                        })
                    })
                }, 300)
            } else {
                addOrUpdateAmount(param).then((res) => {
                    cartUtil.getSupplierCarList(isTime).then((res) => {
                        // uni.hideLoading()
                        resolve(res)
                    })
                })
            }
        })
    },
    //删除、清空购物车
    deleteUserCar: (param, orderType) => {
        return new Promise((resolve, reject) => {
            deleteUserCar(param, orderType).then((res) => {
                if (orderType) {
                    cartUtil.getUserCarList(true, orderType).then((res) => {
                        resolve(true)
                    })
                } else {
                    cartUtil.getUserCarList().then((res) => {
                        resolve(true)
                    })
                }
            })
        })
    },
    //删除、清空购物车(供应商)
    deleteSupplierCar: (param) => {
        return new Promise((resolve, reject) => {
            deleteUserCar(param).then((res) => {
                cartUtil.getSupplierCarList().then((res) => {
                    resolve(true)
                })
            })
        })
    },
}
module.exports = {
    GetUsableOrderProjectList: cartUtil.GetUsableOrderProjectList,

    getCartTotal: cartUtil.getCartTotal,
    getCartTotalForSelect: cartUtil.getCartTotalForSelect,
    updateCart: cartUtil.updateCart,
    deleteUserCar: cartUtil.deleteUserCar,
    getUserCarList: cartUtil.getUserCarList,
    getSupplierCarList: cartUtil.getUserCarList,
    getSupplierCartTotal: cartUtil.getCartTotal,
    getSupplierCartTotalForSelect: cartUtil.getSupplierCartTotalForSelect,
    updateSupplierCart: cartUtil.updateCart,
    deleteSupplierCar: cartUtil.deleteUserCar,
    getMarkSupplierCarList: cartUtil.getMarkSupplierCarList,
}
